package me.pinion.check;

import com.jfinal.core.ActionInvocation;
import me.pinion.check.annotation.AllowMethod;
import me.pinion.check.annotation.CheckBind;
import javax.servlet.http.HttpServletResponse;


@CheckBind(AllowMethod.class)
public class RequestMethodCheck extends AbstractCheck{
    @Override
    public int onRequest(Object anno, ActionInvocation ai) {
        String[] methods = ((AllowMethod)anno).value();
        if(methodAllow(methods, ai)){
            return 0;
        }else {
            ai.getController().renderError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return -1;
        }
    }

    private boolean methodAllow(String[] methods, ActionInvocation ai){
        String requestM = ai.getController().getRequest().getMethod();
        for (String m:methods)
            if (m.toLowerCase().equals(requestM.toLowerCase())){
                return true;
            }
        return false;
    }
}
